package com.navinfo.app.hd

import android.content.Context
import android.os.Message
import android.os.Parcel
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.CheckBox
import android.widget.CompoundButton
import com.navinfo.collect.library.data.entity.LayerEntity
import org.greenrobot.eventbus.EventBus

class HdLayerCheckboxAdapter(context: Context) : BaseAdapter() {
    val listData: MutableList<LayerEntity> = ArrayList()
    val checkedMap: HashMap<String, Boolean> = HashMap()
    val layoutInflate: LayoutInflater by lazy { LayoutInflater.from(context) }

    override fun getCount(): Int {
        return listData.size
    }

    override fun getItem(p0: Int): Any {
        return listData.get(p0)
    }

    override fun getItemId(p0: Int): Long {
        return p0.toLong()
    }

    override fun getView(index: Int, convertView: View?, viewGroup: ViewGroup?): View {
        var view: View = layoutInflate.inflate(R.layout.item_checkbox_hd_layer, null)
        val chkBox: CheckBox = view.findViewById<CheckBox>(R.id.chk_layer_visiable)
        chkBox.isChecked = checkedMap.containsKey(listData[index].layerName)&&checkedMap.get(listData[index].layerName) == true
        chkBox.text = listData[index].layerName
        chkBox.setOnClickListener { view ->
            val checkBox = view as CheckBox
            checkedMap.put(checkBox.text.toString(), checkBox.isChecked)
            // 通知地图刷新
            val msg = Message()
            msg.what = 0x101
            msg.obj = checkedMap
            EventBus.getDefault().post(msg)
        }
        return view
    }

    fun refreshData(layerEntityList: List<LayerEntity>) {
        this.listData.clear()
        this.listData.addAll(layerEntityList)
        this.checkedMap.clear()
        this.listData.stream().forEach {this.checkedMap.put(it.layerName, true)}
    }
}